<?php

session_start();

require_once ("../../../db.php");

if (!isset($_SESSION['uid']) || ($_SESSION['type'] != 'student')) {
    die('Not logged in as an student user');
}

$sql = 'INSERT INTO projectgroups(name, `date`) VALUES (?, now())'; //insert the group to databas
$sth = $db->prepare($sql);
$sth->execute(array($_POST['grpname']));    // with groupname
if ($sth->rowCount() == 1) {
    $sql = 'SELECT LAST_INSERT_ID() as id'; // Find the id of the project
    foreach ($db->query($sql) as $row) {    // add the user to group
        $grpId = $row['id'];
            $sql = 'INSERT INTO groupparticipants(groupid, participantid) VALUES (?, ?)';
            $sth = $db->prepare($sql);
            $sth->execute(array($grpId, $_SESSION['uid']));
    }
    echo json_encode(array('success' => 'group created'));
} else {
    echo json_encode(array('error' => 'no group created'));
}
?>
